/*
 * Copyright (c) 2007
 *	Alberto Magni, Maggioni Marcello
 * 
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 *
 */

package servlets;

import Database.*;
import beans.LoginBean;
import exceptions.*;
import java.io.*;
import java.net.*;

import java.util.List;
import javax.servlet.*;
import javax.servlet.http.*;
import org.apache.tomcat.util.http.fileupload.DiskFileUpload;
import org.apache.tomcat.util.http.fileupload.FileItem;
import parser.Parser;

/**
 * This servlet handles requests from the Administrator configuration page.
 * 
 * @author Marcello Maggioni
 */
public class AdminConfigSrv extends HttpServlet {

    private UsersDB udb;
    private AddressesDB adb;
    private ConfigurationDB cdb;
    
    @Override
    public void init() throws ServletException {
        super.init();
        ServletContext sc = this.getServletContext();
        udb = (UsersDB) sc.getAttribute("usersdb");
        adb = (AddressesDB) sc.getAttribute("addressesdb");
        cdb = (ConfigurationDB) sc.getAttribute("configurationdb");
    }

    @SuppressWarnings("unchecked")
    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        RequestDispatcher rd_correct = request.getRequestDispatcher("admin_configuration.jsp");
        RequestDispatcher rd_error = request.getRequestDispatcher("error.jsp");
        String[] parameters = request.getParameterValues("enable");
        String parameter = null;
        try {
            if (parameters != null) {
                for (String value : parameters) {
                    udb.enableUser(value);
                }
                rd_correct.forward(request, response);
                return;
            }
            parameters = request.getParameterValues("disable");
            if (parameters != null) {
                for (String value : parameters) {
                    udb.disableUser(value);
                }
                rd_correct.forward(request, response);
                return;
            }
            parameters = request.getParameterValues("delete");
            if (parameters != null) {
                for (String value : parameters) {
                    udb.deleteUser(value);
                    adb.removeAddresses(value);
                    cdb.removeConfiguration(value);
                }
                rd_correct.forward(request, response);
                return;
            }
            
            LoginBean lb = (LoginBean) request.getSession().getAttribute("loggedin");
            /*parameter = request.getParameter("username");
            if (parameter != null) {
                udb.changeUsername(lb.getUsername(), parameter);
                adb.changeUsername(lb.getUsername(), parameter);
                request.getRequestDispatcher("LogoutSrv").forward(request, response);
                return;
            }*/
            parameter = request.getParameter("passwordone");
            String parameter2 = request.getParameter("passwordtwo");
            if (parameter != null && parameter2 != null) {
                if (parameter.equals(parameter2)) {
                    udb.changePassword(lb.getUsername(), parameter);
                    rd_correct.forward(request, response);
                    return;
                } else {
                    request.setAttribute("exception", new PasswordDontMatchException());
                    rd_error.forward(request, response);
                    return;
                }
            }
            DiskFileUpload dfu = new DiskFileUpload();
            if (dfu.isMultipartContent(request)) {
                List<FileItem> lfi = dfu.parseRequest(request);
                FileItem fi = lfi.get(0);
                Parser parser = new Parser();
                
                String [] addresses=null;
                addresses = parser.getAddresses(fi);
                
                
                
                adb.setAddresses(addresses, lb.getUsername(), fi.getName());
                rd_correct.forward(request, response);
                return;
            }
            parameter = request.getParameter("server");

            if (parameter != null) {
                cdb.setServer(null, parameter);
                rd_correct.forward(request, response);
                return;
            }

            parameter = request.getParameter("mail");

            if (parameter != null) {
                cdb.setEMailAddress(null, parameter);
                rd_correct.forward(request, response);
                return;
            }

            parameter = request.getParameter("spamcheck");
            if (request.getParameter("spamcheckbut") != null) {
                if (parameter != null && !cdb.getSpamCheck(null)) {
                    cdb.setSpamCheck(null, true);
                    rd_correct.forward(request, response);
                    return;
                } else if (parameter == null && cdb.getSpamCheck(null)) {
                    cdb.setSpamCheck(null, false);
                    rd_correct.forward(request, response);
                    return;
                }
            }
            
            parameter = request.getParameter("srvauth");
            if (request.getParameter("srvauthbut") != null) {
                if (parameter != null && !cdb.getServerAuthMode(null)) {
                    cdb.setServerAuthMode(null, true);
                    rd_correct.forward(request, response);
                    return;
                } else if (parameter == null && cdb.getServerAuthMode(null)) {
                    cdb.setServerAuthMode(null, false);
                    rd_correct.forward(request, response);
                    return;
                }
            }
            
            parameter = request.getParameter("download");
            if (parameter != null) {
                byte[] xml_rep = adb.xmlByteRepresentation(lb.getUsername());
                ServletOutputStream sos = response.getOutputStream();
                response.setContentType("text/xml");
                response.setHeader("Content-Disposition","attachment; filename=addresses.xml");
                response.setContentLength(xml_rep.length);
                sos.write(xml_rep);
                sos.flush();
                sos.close();
                return;
            }
        }
        catch (Exception ex) {
            request.setAttribute("exception", ex);
            rd_error.forward(request, response);
        }

    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
    * Handles the HTTP <code>GET</code> method.
    * @param request servlet request
    * @param response servlet response
    */
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    } 

    /** 
    * Handles the HTTP <code>POST</code> method.
    * @param request servlet request
    * @param response servlet response
    */
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
    * Returns a short description of the servlet.
    */
    public String getServletInfo() {
        return "Short description";
    }
    // </editor-fold>
}
